#include <windows.h>
#include <wininet.h>
#include "main.h"

#pragma comment(lib, "wininet.lib")

static unsigned dummy_size;

extern char *download(char *link, unsigned *size)
{
	unsigned prealloc_size = 100 * 1024;
	char *buf = malloc(prealloc_size);
	DWORD num;
	HINTERNET hinet, hurl;
	*size = 0;

	DEBUG_PRINTF("Downloading [%s].\n", link);
	
	hinet = InternetOpen("Microsoft Internet Explorer",
		INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_INVALID_PORT_NUMBER);
	hurl = InternetOpenUrl(hinet, link, NULL, 0, INTERNET_FLAG_NEED_FILE, 0);
 
	DEBUG_PUTS("Connected. Reading remote data.");
 
	while (TRUE == InternetReadFile(hurl, buf + *size, 1024, &num) && num > 0)
	{
		*size += num;
		
		if (*size + 1024 > prealloc_size)
		{
			prealloc_size += prealloc_size / 2;
			buf = realloc(buf, prealloc_size);
		}
	}
	
	InternetCloseHandle(hurl);
	InternetCloseHandle(hinet);
	
	DEBUG_PUTS("Downloaded successfully.");
	// DEBUG_PUTS(buf);
	
	return buf;
}

extern char *download_string(char *link)
{
	return download(link, &dummy_size);
}

extern char *download_utf8_to_gb2312(char *link)
{
	char *utf8 = download(link, &dummy_size),
		*gb2312 = utf8_to_gb2312(utf8);
	free(utf8);
	return gb2312;
}

typedef char *unzip_func_t(char *data, unsigned ssize, unsigned *size);

static char *download_and_decompress(char *link, unzip_func_t unzip_func)
{
	unsigned size, webpage_size, size_unzipped;
	char *buf = download(link, &size);
	char *unzipped = unzip_func(buf, size, &size_unzipped);
	free(buf);
	
	return unzipped;
}

extern char *download_gzip(char *link)
{
	extern unzip_func_t unzip_gzip;
	return download_and_decompress(link, unzip_gzip);
}

extern char *download_deflate(char *link)
{
	extern unzip_func_t unzip_deflate;
	return download_and_decompress(link, unzip_deflate);
}
